package com.cy.bus.ui;

import java.util.Timer;
import java.util.TimerTask;

import com.cy.utils.SysParam;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

/**
 * webActivity
 * @author CY
 *
 */
@SuppressLint("SetJavaScriptEnabled")
public class WebActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener {
	
	private WebView webView;
	private String url;
	private ProgressBar progressBar;
	
	private static final int REFRESH_COMPLETE = 0X110;
	private SwipeRefreshLayout mSwipeLayout;
	
	private static Boolean isExit = false;  
	
	/**
	 * 获取刷新对象
	 * @return
	 */
	public SwipeRefreshLayout getmSwipeLayout() {
		return mSwipeLayout;
	}

	/** 
	 * 双击退出函数 
	 */  
	private void exitBy2Click() {
	    Timer tExit = null;  
	    if (isExit == false) {  
	        isExit = true; // 准备退出  
	        tExit = new Timer();  
	        tExit.schedule(new TimerTask() {  
	            @Override  
	            public void run() {  
	                isExit = false; // 取消退出  
	            }  
	        }, 1000); // 如果1秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务  
	    } else {  
	        this.finish();  
	    }
	}
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			switch (msg.what)
			{
			case REFRESH_COMPLETE:
				webView.reload();
				Toast.makeText(WebActivity.this, "刷新成功", Toast.LENGTH_SHORT).show();
				mSwipeLayout.setRefreshing(false);
				break;

			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent intent = getIntent();
		Bundle data = intent.getExtras();
		Boolean noRefresh = false;
		if(!data.isEmpty()) {
			url = data.getString("url");
			noRefresh = data.getBoolean("noRefresh");
		}
		getActionBar().setDisplayShowHomeEnabled(false);
		if(SysParam.read("full").equals("false")) {
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    	} else {
    		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    	}
		setContentView(R.layout.activity_webview);
		setProgressBarVisibility(true);
		initWebView();
		
		mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.web_swipe_ly);

		mSwipeLayout.setOnRefreshListener(this);
		mSwipeLayout.setColorScheme(android.R.color.holo_green_dark, android.R.color.holo_green_light,
				android.R.color.holo_orange_light, android.R.color.holo_red_light);
		mSwipeLayout.setEnabled(!noRefresh);
	}

	/**
	 * 初始化webView
	 */
	private void initWebView() {
		webView = (WebView) findViewById(R.id.webview);
		//支持JavaScript
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setGeolocationEnabled(true);
		webView.getSettings().setGeolocationDatabasePath(getFilesDir().getPath());
		webView.getSettings().setDomStorageEnabled(true);
		webView.loadUrl(url);
		webView.setWebViewClient(new WebViewClient(){
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}
		});
		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				if(newProgress == 100) {
					WebActivity.this.setTitle(webView.getTitle());
					progressBar.setVisibility(View.INVISIBLE);
				} else {
					WebActivity.this.setTitle("加载中");
				}
			}
			@Override
			  public void onGeolocationPermissionsHidePrompt() {
			      super.onGeolocationPermissionsHidePrompt();
			  }
			@Override
			public void onGeolocationPermissionsShowPrompt(final String origin,
					final Callback callback) {
				AlertDialog.Builder builder = new AlertDialog.Builder(WebActivity.this);
			      builder.setMessage("Allow to access location information?");
			      OnClickListener dialogButtonOnClickListener = new OnClickListener() {

			          @Override
			          public void onClick(DialogInterface dialog, int clickedButton) {
			              if (DialogInterface.BUTTON_POSITIVE == clickedButton) {
			                  callback.invoke(origin, true, true);
			              } else if (DialogInterface.BUTTON_NEGATIVE == clickedButton) {
			                  callback.invoke(origin, false, false);
			              }
			          }
			      };
			      builder.setPositiveButton("Allow", dialogButtonOnClickListener);
			      builder.setNegativeButton("Deny", dialogButtonOnClickListener);
			      builder.show();
			      super.onGeolocationPermissionsShowPrompt(origin, callback);
			}
			  
		});
		// 优先使用缓存
		webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exitBy2Click();
			if (webView.canGoBack()) {
				webView.goBack();// 返回上一页面
				return true;
			} else {
				this.finish();
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.web, menu);
		progressBar = (ProgressBar) menu.findItem(R.id.webView_actionbar_loading).getActionView();
		return true;
	}

	@Override
	public void onRefresh() {
		mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE,2000);
		
	}
}
